function[meanVecs, varVec] = trainForMahalanobis(trainingSet)
% Calculates the mean vector for every class as well as the covariance
% matrix, which is assumed to be diagonal and the same for every class.
%
%   INPUT
%   trainingSet.The feature vectors for training.
%   OUTPUT
%   meanVecs....An array of the mean feature vector of every class.
%   varVec......The diagonal of the covariance matrix as a vector.

    classes = unique(trainingSet(1, :));
    meanVecs = zeros(size(trainingSet, 1) - 1, size(classes, 2));
    covarMat = zeros(size(trainingSet, 1) - 1);
    for class = classes
        classVecs = trainingSet(2:end, trainingSet(1, :) == class);
        N = size(classVecs, 2);
        meanVecs(:, class) = sum(classVecs, 2) ./ N;
        xMinusMean = classVecs - (meanVecs(:, class) * ones(1, N));
        for i = 1 : N
            covarMat = covarMat + xMinusMean(:, i) * xMinusMean(:, i)';
        end
    end
    covarMat = covarMat / size(trainingSet, 2);
    varVec = diag(covarMat);
end
